#include "appinc.h"
#include "sans_demo.h"

#define SENSOR_DEMO_NUM 20
int sensor_demo[SENSOR_DEMO_NUM];


static cJSON *sensor_create_data(void)
{
	cJSON *data;
	int i;
	char name[16];

	data = cJSON_CreateObject();
	if (data == NULL)
		return NULL;

	for (i = 0; i < SENSOR_DEMO_NUM; i++) {
		sprintf(name, "demo%d", i);
		cJSON_AddNumberToObject(data, name, sensor_demo[i]);
	}

	return data;
}


static int sensor_set_item(cJSON *sensor)
{
	int i, ret = -1;
	char name[16];
	cJSON *json_i;

	for (i = 0; i < SENSOR_DEMO_NUM; i++) {
		sprintf(name, "demo%d", i);
		json_i = cJSON_GetObjectItem(sensor, name);
		if (json_i && json_i->type == cJSON_Number)
			sensor_demo[i] = json_i->valueint;
	}

	return 0;
}


static int sans_sensor_get(void *obj, ssiot_message_t *msg, cJSON *data)
{
	char *path = "";

	if (data && data->type == cJSON_Object) {
		data = cJSON_GetObjectItem(data, "path");
		if (data && data->valuestring)
			path = data->valuestring;
	}

	data = sensor_create_data();
	if (data == NULL)
		return -ENOMEM;
	if (*path != '\0')
		json_retian(data, path);
	if (data->child == NULL)
		data->type = cJSON_NULL;
	msg->resp_code = SSCODE_OK;
	msg->resp_data = data;

	return 0;
}


static int sans_sensor_set(void *obj, ssiot_message_t *msg, cJSON *data)
{
	int ret;

	if (data == NULL || data->type != cJSON_Object) {
		msg->resp_code = SSCODE_ERR_REQUEST;
		msg->resp_msg = "request invalid";
		return -EFAULT;
	}

	ret = sensor_set_item(data);
	msg->resp_code = (ret == 0 ? SSCODE_OK : SSCODE_ERR_SERVER);

	return 0;
}


int sans_sensor(void *obj, const char *topic, ssiot_message_t *msg)
{
	if (!strcmp(topic, "get"))
		return sans_sensor_get(obj, msg, msg->data);
	else if (!strcmp(topic, "set"))
		return sans_sensor_set(obj, msg, msg->data);
	
	return -EINVAL;
}


int sensor_demo_send(void)
{
	cJSON *data;
	int i;

	for (i = 0; i < SENSOR_DEMO_NUM; i++) {
		sensor_demo[i]++;
	}

	data = sensor_create_data();
	ssiot_send_data(NULL, NULL, -1, "sensor", data);
	cJSON_Delete(data);

	return 0;
}

